
package cnhy.salary.controller;

import cn.hutool.core.date.DateUtil;
import cnhy.salary.mapper.SalaryMapper;
import com.easy.query.api4j.sql.SQLWherePredicate;
import com.easy.query.api4j.util.EasyLambdaUtil;
import com.easy.query.core.expression.lambda.SQLExpression1;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.*;
import ling.common.domain.entity.IDeptEntity;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.util.*;
import java.util.function.Function;
import java.util.function.Supplier;

import lombok.*;
import com.ruoyi.common.core.page.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import cnhy.salary.domain.DeathProof;
//import cnhy.salary.service.DeathProofService;
import ling.common.*;
import ling.common.domain.*;

/** 证明单 控制层
 * @author : He-LiangLiang@Outlook.com
 * @date : 2025-7-10
 */
@Api(tags = "证明单 功能接口")
@RestController
@RequestMapping("/salary/DeathProof")
public class DeathProofController extends EQueryController<DeathProof>{


    @Resource
    SalaryMapper mapper;
    @Resource
    ISysConfigService configService;
    static String certificateIdPrefix;
     String gotCertificateIdPrefix() {
        if (StringUtils.isEmpty(certificateIdPrefix)) {
            certificateIdPrefix = configService.selectConfigByKey("prf.certificateIdPrefix");
            if (StringUtils.isEmpty(certificateIdPrefix))
                certificateIdPrefix = "MJY866366";
        }
        return certificateIdPrefix;
    }
    @GetMapping(value = "/orlPatient")
    public Result orlPatient(String patientNo) {

        var map = new HashMap<String,Object>();
        map.put("PATIENT_NO", patientNo);
        var re = mapper.orlPatient(map);
        return Result.ok(re);
    }
    @ApiOperation("详情")
    //@PreAuthorize("@ps.any(@pay.DeathProof.query)")
    @GetMapping(value = "/{id}")
    public Result<DeathProof> getInfo(@PathVariable("id") Long id)
    {
        return super.getInfo(id);
    }
    @FunctionalInterface
    public static interface MethodRef<T,T2,R> extends Serializable {
        R apply(T target,T2 pam) throws Exception;
    }
    @SneakyThrows
    <T,T2,R> String myBatisSqlGet(MethodRef<T,T2,R> fun) {//Function<T,R> fun
        //https://www.cnblogs.com/Ashiamd/p/17575020.html
        var ff = fun.getClass();
        var method = fun.getClass().getDeclaredMethod("writeReplace");
        method.setAccessible(true);
        var lambda = (SerializedLambda) method.invoke(fun);
        var mname = lambda.getImplClass().replace("/", ".") + "." +
                lambda.getImplMethodName();
        return SpringUtils.getBean(SqlSessionFactory.class).getConfiguration()
                .getMappedStatement(mname)
                .getBoundSql(null).getSql();
    }
    @ApiOperation("分页列表")
    //@PreAuthorize("@ps.any(@pay.DeathProof.list)")
    @GetMapping("list")
    @DataScope
    public ResultRows<DeathProof> list(DeathProof dto, PageDomain pageRequest) {

        SQLExpression1<SQLWherePredicate<DeathProof>> where=null;
//        if(dto.getIsMy()!=null&&dto.getIsMy()==true)
//        {
//            where=p->p.eq(DeathProof::getCreatedId,getUserId());
//        }
        return queryPage(dto,pageRequest,where);
    }

    @ApiOperation("新增")
    //@PreAuthorize("@ps.any(@pay.DeathProof.add)")
    @Log(title = "证明单", businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated @RequestBody DeathProof entity) {
        entity.setDeptId(getDeptId());
        var old = queryHelper.queryable(DeathProof.class)
                .orderByDesc(p -> p.column(DeathProof::getCreatedTime))
                .orderByDesc(p -> p.column(DeathProof::getNum))
                .firstOrNull();
        var oldNum = 0;
        var oldYear = DateUtil.date(old.getCreatedTime()).year();
        var nowYear = DateUtil.date().year();
        oldNum = old.getNum() == null ? 0 : old.getNum();
        if (nowYear > oldYear)
            oldNum = 0;
        entity.setCreatedTime(new Date());
        var prefix = gotCertificateIdPrefix();
        entity.setNum(++oldNum);
        entity.setCertificateId(prefix + DateUtil.date(entity.getCreatedTime()).year() + String.format("%04d", entity.getNum()));
        if (entity.getStatus() == null)
            entity.setStatus(0);
        entity.setIsDelete(0);
        var re = super.add(entity);
        return Result.restResult(entity, re.getCode(), re.getMsg());
    }

    @ApiOperation("删除")
    @PreAuthorize("@ps.any(@pay.DeathProof.remove)")
    @Log(title = "证明单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result remove(@PathVariable("ids") Long[] ids){
        return super.remove(Arrays.stream(ids).toArray());
    }

    @ApiOperation("编辑")
    @PreAuthorize("@ps.any(@pay.DeathProof.edit)")
    @Log(title = "证明单", businessType = BusinessType.UPDATE)
    @PutMapping
    public  Result edit(@Validated @RequestBody DeathProof entity){
//         var old=getInfo(entity.getId());
//         if(old.getData().getStatus()==1)
//             return Result.bad("已确认单据不能编辑");
        return super.edit(entity);
    }

    @ApiOperation("导出")
    @PreAuthorize("@ps.any(@pay.DeathProof.export)")
    @Log(title = "证明单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(DeathProof entity, PageDomain pageRequest,HttpServletResponse response)
    {
        super.export(entity,pageRequest,null,response);
    }
}